import 'package:flutter_app/bean/list_integral_info_entity.dart';
import 'package:flutter_app/manager/AppSetInfoManager.dart';
import 'package:flutter_app/network/Api.dart';
import 'package:flutter_app/network/ResultData.dart';
import 'package:flutter_app/utils/toast_utils.dart';
import 'package:get/get.dart';
import 'package:pull_to_refresh/pull_to_refresh.dart';

import '../../WebViewPage.dart';
import 'accumulate_points_state.dart';

class AccumulatePointsLogic extends GetxController {
  final AccumulatePointsState state = AccumulatePointsState();

  late RefreshController refreshController; // 刷新控制器

  String year = "";

  List<String> yearItems = [];

  @override
  void onInit() {
    super.onInit();
    // initialRefresh 是否最初刷新
    refreshController = RefreshController(initialRefresh: false);
    yearItems = Get.arguments['yearItems'];
    year = Get.arguments['year'];
  }

  @override
  void onReady() {
    super.onReady();
    listIntegralInfo(state.currentPage);
  }

  /// 获取积分明细
  Future<void> listIntegralInfo(int currentPage) async {
    Map<String, dynamic> page = {
      "year": year,
    };
    Map<String, dynamic> param = {
      "currentPage": currentPage,
      'pageSize': 15,
      'param': page,
    };
    ResultData resultData = await Api.listIntegralInfo(param);
    if (resultData.isSuccess) {
      if (currentPage == 1) {
        state.listIntegralInfoEntity = ListIntegralInfoEntity.fromJson(resultData.data['data']);
      } else if (currentPage > 1) {
        state.listIntegralInfoEntity!.content!.addAll(ListIntegralInfoEntity.fromJson(resultData.data['data']).content!);
      }
      update();
    } else {
      toast.show(resultData.data["message"]);
    }
  }

  /// 刷新
  void onRefresh() async {
    state.currentPage = 1;
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果失败,使用refreshFailed ()
    listIntegralInfo(state.currentPage).then((_) {
      refreshController.refreshCompleted();
      refreshController.resetNoData();
    });
  }

  /// 加载
  void onLoading() async {
    // 监视网络获取
    await Future.delayed(Duration(milliseconds: 1000));
    // 如果完成使用loadFailed()，如果没有数据返回，使用LoadNodata()
    int? totalPages = state.listIntegralInfoEntity?.totalPages ?? 1;
    if (state.currentPage < totalPages) {
      state.currentPage++;
      listIntegralInfo(state.currentPage).then((_) {
        refreshController.loadComplete();
      });
      update();
    } else {
      refreshController.loadNoData();
    }
  }

  goToWebViewPage() => Get.to(() => WebViewPage(
        title: '积分说明',
        url: AppSetInfoManager().getAccumulateUrl(),
      ));

  @override
  void onClose() {
    super.onClose();
  }
}
